package com.ls.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ls.blog.entity.SysUser;
import com.ls.blog.exception.ParameterIsNullException;
import com.ls.blog.exception.UserExitException;
import com.ls.blog.mapper.SysUserMapper;
import com.ls.blog.api.SysUserService;
import com.ls.blog.api.TokenService;
import com.ls.blog.vo.Author;
import com.ls.blog.vo.UserInfo;
import com.ls.blog.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @program: myblog
 * @author: lishun
 * @create: 2021-07-05 00:16
 **/
@Service
public class SysUserServiceImpl implements SysUserService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TokenService tokenService;


    @Override
    public SysUser findSysUserById(Long userId) {
        SysUser sysUser = sysUserMapper.selectById(userId);
        if (sysUser == null) {
            sysUser = new SysUser();
            sysUser.setNickname("ls");
        }
        return sysUser;
    }


    @Override
    public SysUser findByUsername(String account) {
        System.out.println(account);
        SysUser sysUser = sysUserMapper.selectUserByAccount(account);
        return sysUser;
    }


    @Override
    @Transactional
    public void register(SysUser sysUser) throws Exception {
        /**
         * 判断注册用户是否为空
         * 判断用户是否已经被注册
         * 密码加密，省略
         * 注册(添加上事务)
         */
        if (sysUser==null){
            throw new ParameterIsNullException("参数为空");
        }

        if (findByUsername(sysUser.getAccount())!=null){
            throw new UserExitException("用户存在");
        }

        /**
         * 这里应该还要有其他设置
         */
        // 添加用户
        sysUserMapper.insert(sysUser);
    }

    /**
     * 根据token获得当前用户信息
     * @param token
     * @return
     */
    @Override
    public UserInfo currentUser(String token) throws Exception {

        UserInfo info = tokenService.tokenParse(token);
        return info;
    }

    @Override
    public Author getAuthorById(Long authorId) {
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper();
        queryWrapper.select("id","nickName","avatar");
        queryWrapper.eq("id",authorId);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        Author author = new Author();
        BeanUtils.copyProperties(sysUser,author);
        return author;
    }

    @Override
    public List<UserVo> findUserList(Long current,Long size) {
        Page<SysUser> page = new Page<>(current,7);

        List<UserVo> userList = sysUserMapper.findUserList(page);
        return userList;
    }
}
